package practice.tmp;

import java.util.ArrayList;
import java.util.List;

public class Solution22 {
    List<String> res = new ArrayList<>();
    StringBuffer sb = new StringBuffer();

    public List<String> generateParenthesis(int n) {
        back(n, n);
        return res;
    }

    public void back(int left, int right) {
        if (left == 0 && right == 0) {
            res.add(sb.toString());
        }
        if (right < left) return;
        if (left >= 0) {
            sb.append('(');
            back(left - 1, right);
            sb.deleteCharAt(sb.length() - 1);
        }
        if (right >= 0) {
            sb.append(')');
            back(left, right - 1);
            sb.deleteCharAt(sb.length() - 1);
        }
    }
}
